<?php
 /**
 *  +---------------------------------------------------------------------- 
 *  | 文件功能：权限菜单相关功能控制器
 *  +---------------------------------------------------------------------- 
 *  | Copyright (c) 2022~2024 https://www.huihuiv.com All rights reserved.
 *  +---------------------------------------------------------------------- 
 *  | Create At: 2024年02月26日 18:04:42
 *  +---------------------------------------------------------------------- 
 *  | Author: 半壶水 <star@cqshanwen.com>
 *  +---------------------------------------------------------------------- 
 */

namespace App\Http\Controllers\Api;

use App\Interface\CurdController;
use App\Librarys\Message;
use App\Librarys\Sort;
use App\Models\AuthModel;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class AuthController extends BaseController implements CurdController
{

    protected Request $request;
    protected AuthModel $authModel;

    public function __construct(Request $request, AuthModel $authModel)
    {
        $this->request = $request;
        $this->authModel = $authModel;
    }

    /**
     * 创建/修改权限菜单
     *
     * @return JsonResponse
     */
    public function create(): JsonResponse
    {
        // 获取操作标志
        $flag = $this->request->flag;

        // switch匹配对应操作
        switch ($flag) {
            case 'create':
                // 获取创建必要参数
                $auth['pid'] = $this->request->pid;
                $auth['title'] = $this->request->title;
                $auth['controller'] = $this->request->controller;
                $auth['action'] = $this->request->action;
                $auth['icon'] = $this->request->icon;
                $auth['router'] = $this->request->router;
                $auth['type'] = $this->request->type;
                $auth['is_hidden'] = $this->request->is_hidden;

                // 验证必要条件是否可用
                $validate = Validator::make($auth, [
                    'pid' => 'required',
                    'title' => 'required|unique:sw_auth',
                ], [
                    'pid.required' => '父级权限菜单不能为空',
                    'title.required' => '权限菜单名称不能为空',
                    'title.unique' => '权限菜单名称已经存在'
                ]);

                // 判断是否验证通过
                if ($validate->fails()) {
                    // 验证失败
                    return Message::show(false, $validate->errors()->first());
                }

                // 验证通过，开启事务
                DB::beginTransaction();
                try {
                    // 尝试写入数据
                    $this->authModel->create($auth);
                    // 提交事务
                    DB::commit();
                    return Message::show(true, '权限菜单创建成功');
                } catch (Exception $error) {
                    // 写入失败，数据回滚
                    DB::rollBack();
                    return Message::show(false, '权限菜单创建失败：' . $error->getMessage());
                }

                break;
            case 'update':
                // 获取修改必要参数
                $auth['auth_id'] = $this->request->auth_id;
                $auth['pid'] = $this->request->pid;
                $auth['title'] = $this->request->title;
                $auth['controller'] = $this->request->controller;
                $auth['action'] = $this->request->action;
                $auth['icon'] = $this->request->icon;
                $auth['router'] = $this->request->router;
                $auth['type'] = $this->request->type;
                $auth['is_hidden'] = $this->request->is_hidden;


                // 验证必要条件是否可用
                $validate = Validator::make($auth, [
                    'auth_id' => 'required',
                    'pid' => 'required',
                    'title' => 'required',
                ], [
                    'auth_id.required' => '修改必要条件不能为空',
                    'pid.required' => '父级权限菜单不能为空',
                    'title.required' => '权限菜单名称不能为空',
                ]);

                // 判断是否验证通过
                if ($validate->fails()) {
                    // 验证失败
                    return Message::show(false, $validate->errors()->first());
                }

                // 验证通过，开启事务
                DB::beginTransaction();
                try {
                    // 尝试写入数据
                    $this->authModel->where(['auth_id' => $auth['auth_id']])->update($auth);
                    // 提交事务
                    DB::commit();
                    return Message::show(true, '权限菜单修改成功');
                } catch (Exception $error) {
                    // 写入失败，数据回滚
                    DB::rollBack();
                    return Message::show(false, '权限菜单修改失败：' . $error->getMessage());
                }

                break;
            default:
                // 未定义操作
                return Message::show(false, '未定义操作');
                break;
        }
    }

    /**
     * 获取权限菜单信息
     *
     * @return JsonResponse
     */
    public function query(): JsonResponse
    {
        // 获取操作标志
        $flag = $this->request->flag;

        // switch匹配对应操作
        switch ($flag) {
                // 获取无格式列表
            case 'normal':
                $groupList = $this->authModel->get();
                return Message::show(true, '获取成功', $groupList);
                break;
                // 获取表格数据格式
            case 'table':
                // 获取所有权限列表
                $authList = $this->authModel->get();
                // 生成权限树
                $authTree = Sort::build_auth_tree(0, $authList);
                return Message::show(true, '获取成功', $authTree);
                break;
                // 获取可选择权限树
            case 'select_tree':
                // 获取所有权限列表
                $authList = $this->authModel->get();
                // 生成权限树
                $authTree = Sort::build_auth_select_tree(0, $authList);
                return Message::show(true, '获取成功', $authTree);
                break;
            default:
                return Message::show(false, '未定义操作');
                break;
        }
    }

    public function delete()
    {
        // 获取必要参数
        $auth_id = $this->request->auth_id;
        // 判断是否存在子菜单
        if ($this->authModel->where(['pid' => $auth_id])->exists()) {
            // 存在子菜单，不可删除
            return Message::show(false, '当前菜单下含有子菜单，无法删除');
        }
        // 不存在子菜单
        // 开启事务
        DB::beginTransaction();
        try {
            // 删除数据
            $this->authModel->where(['auth_id' => $auth_id])->delete();
            // 提交事务
            DB::commit();
            return Message::show(true, '删除成功');
        } catch (Exception $error) {
            // 数据回滚
            DB::rollBack();
            return Message::show(false, $error->getMessage());
        }
    }
}
